<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" href="../rurple.css" type="text/css" />

<title>Random escapes</title>
</head>
<body>
<h2 class="title">40. Random escapes</h2>

<p>Reeborg the <code>RefurbishedRobot</code> carries inside him some "electronic dice". He can "roll the dice" and decide what to do based on the result.  Such a decision, based on an unpredictable result like the roll of dice, is called a <em>random</em> decision.  We are going to write a couple of programs that will let Reeborg <em>eventually</em> get out of a maze by making random decisions.  Here's the basic algorithm that Reeborg will follow:</p>

<ul>
<li>
Reeborg checks if he can take a step forward.
</li>
<ul>
<li>
If so, Reeborg takes the step forward, and check to see if he is out of the maze.
</li>
<ul>
<li>
If so, Reeborg turns itself off.
</li>
<li>
If not, Reeborg continues, trying to find his way out.
</li>
</ul>
</ul>
<li>
Reeborg is not out of the maze; he rolls his dice and decides in which direction the next step is going to be taken (left, right, or in the original direction), and turn in that direction if required.
</li>
<li>
Reeborg goes back to the beginning of this algorithm, checking if he can take a step forward.
</li>
</ul>

<p>We will implement this algorithm using two different type of approaches to dealing with potential problems.</p>

<h3 class="section">Random escape 1</h3>

<p>Our first program will be based on the techniques we have seen up to now.  We ask Reeborg to check for the presence of a wall in front and to move only if there is none present.  This is sometimes describe as a <i>Look before you leap</i> (LBYL) approach.</p>

<pre>
G = RefurbishedRobot()
G.set_delay(0) <span class="comment"># moving as fast as possible</span>
<span class="keyword">while</span> True:
    <span class="keyword">if</span> G.front_is_clear():
        G.move()
        <span class="keyword">if</span> G.on_beeper():
            G.turn_off()
    r = G.roll_dice()
    <span class="keyword">if</span> r <span class="keyword">in</span> [1, 2]:
        G.turn_left()
    <span class="keyword">elif</span> r <span class="keyword">in</span> [3, 4]:
        G.turn_right()
</pre>

<p>We have set the time delay to the minimum value (hence, the fastest speed) as it can take quite a while to find the exit!  When Reeborg "roll the dice", 6 different results are possible (the numbers 1 to 6).  The example below shows one possible outcome.</p>

<p><img alt="random maze solution" src="../../images/inter/random_maze.png" /></p>

<h3 class="section">Exceptions</h3>

<p>To deal with unusual conditions, Python programmers often use "Exceptions".  For example, if you try to divide a number by zero, Python will complain in the following way:</p>

<pre>
>>> x = 1/0
Traceback (most recent call last):
  File "&lt;input>", line 1, in ?
ZeroDivisionError: integer division or modulo by zero
</pre>

<p>Python responded by "raising" a particular "Exception" (ZeroDivisionError) which resulted in the error message (or Traceback) displayed above.  This process of "raising" exceptions is a way that Python program can alert the user about situations with which it does not know how to deal.  We can simulate this by using the Python keyword <span class="keyword">raise</span></p>

<pre>
>>> <span class="keyword">raise</span> ZeroDivisionError
Traceback (most recent call last):
  File "&lt;input>", line 1, in ?
ZeroDivisionError
</pre>

<p>When we know that a particular exception might be raised, we can "catch" it and deal with it in a way that might make sense.  Here's how we do this:</p>

<pre>
>>> <span class="keyword">try</span>:
...     x = 1/0
... <span class="keyword">except</span>:
...     <span class="keyword">print</span> "You have attempted to divide by zero. This is not allowed."
...
You have attempted to divide by zero. This is not allowed.
</pre>

<p>Let us use this to write a second program to get Reeborg out of the maze.</p>

<h3 class="section">Random escape 2</h3>

<p>When a problem is encountered by Reeborg (hitting a wall, trying to pick up a non-existent beeper, etc.), an exception is raised.  This normally ends the robot program and is "caught" by RUR-PLE to display the appropriate error dialog.  If it makes sense, we can write our own program to "catch" this exception and ignore it to allow the program to continue.  This is what we do in the program below.  This is sometimes describe as a <i>Better to ask forgiveness than permission</i> (BAFP) approach.</p>

<pre>
G = RefurbishedRobot()
G.set_delay(0) <span class="comment"># moving as fast as possible</span>
<span class="keyword">while</span> True:
    <span class="keyword">try</span>:
        G.move()
        <span class="keyword">if</span> G.next_to_a_beeper():
            G.turn_off()
    <span class="keyword">except</span> HitWallException:
        <span class="keyword">pass</span>
    r = G.roll_dice(3) <span class="comment"># possible values: 1, 2, 3</span>
    <span class="keyword">if</span> r == 1:
        G.turn_left()
    <span class="keyword">elif</span> r == 2:
        G.turn_right()
</pre>

<p>In the example above, we have used different kinds of dice, one with three possible outcome. You can ask Reeborg to use dice with an arbitrary number of possible outcomes to design your own program.</p>

<h3 class="section">Which approach is preferable?</h3>

<p>If an exceptional condition is not expected to occur often, the BAFP approach is preferred.  However, if the exceptional condition is expected to occur often (as is the case here), the LBYL approach, that we used in the first example, is recommended.</p>

<div class="lessons_nav">
<a href="39-import.htm"><img alt="previous" src=
"../../images/previous.png" />Avoiding repetitions - the important stuff</a>
- <a href="../lessons_toc.htm"><img alt="home" src="../../images/home.png" /></a>
- <a href="../advanced/41-fairy_tale.htm">A Robotic Fairy Tale <img alt="next"
src="../../images/next.png" /></a>
</div>
</body>
</html>
